//
//  TTIClient.m
//  AFNetWorkingDemo
//
//  Created by zym on 14-8-8.
//  Copyright (c) 2014年 翔傲信息科技（上海）有限公司. All rights reserved.
//

#import "TTIClientManager.h"
#import "TTIClientConfig.h"
#import <AFNetworkActivityLogger.h>
#import <AFNetworkActivityIndicatorManager.h>
#import "AppMacro.h"


@interface TTIClientManager ()

@end


@implementation TTIClientManager


-(id)init{
    self = [super init];
    if (self) {
        //设置baseurl
        self.manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:NET_BASEURL]];
        
        // https ssl verification
        [_manager setSecurityPolicy:[self customSecurityPolicy]];
        
        //AF2.0默认是使用AFJSONResponseSerializer自行对JSON进行解析。（如果请求成功，但是JSON无法解析，错误代码为3840）
        //想要AF2.0使用第三方解析，那么需要将设置为AFHTTPResponseSerializer即可，那么返回值为respondata，需要自己解析。  AFJSONResponseSerializer
        _manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        _manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        
        
        //AF2.0只支持text/json，application/json，text/javascript三种格式，如果需要支持其他格式，请自行添加。
        _manager.responseSerializer.acceptableContentTypes = [_manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
        [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
        
        
        [[AFNetworkActivityLogger sharedLogger] setLevel:AFLoggerLevelDebug];
        [[AFNetworkActivityLogger sharedLogger] startLogging];
    
    }
    return self;
}

- (AFSecurityPolicy*)customSecurityPolicy
{
    // /先导入证书
    NSString *cerPath = [[NSBundle mainBundle] pathForResource:Certificate_name ofType:Certificate_type];//证书的路径
    NSData *certData = [NSData dataWithContentsOfFile:cerPath];
    
    // AFSSLPinningModeCertificate 使用证书验证模式
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
    
    // allowInvalidCertificates 是否允许无效证书（也就是自建的证书），默认为NO
    // 如果是需要验证自建证书，需要设置为YES
    securityPolicy.allowInvalidCertificates = YES;
    
    //validatesDomainName 是否需要验证域名，默认为YES；
    //假如证书的域名与你请求的域名不一致，需把该项设置为NO；如设成NO的话，即服务器使用其他可信任机构颁发的证书，也可以建立连接，这个非常危险，建议打开。
    //置为NO，主要用于这种情况：客户端请求的是子域名，而证书上的是另外一个域名。因为SSL证书上的域名是独立的，假如证书上注册的域名是www.google.com，那么mail.google.com是无法验证通过的；当然，有钱可以注册通配符的域名*.google.com，但这个还是比较贵的。
    //如置为NO，建议自己添加对应域名的校验逻辑。
    securityPolicy.validatesDomainName = NO;
    
    securityPolicy.pinnedCertificates = @[certData];
    
    return securityPolicy;
}


-(void)parseResponse:(id)response
           operation:(AFHTTPRequestOperation *)operation
           success:(void(^)(AFHTTPRequestOperation *operetion,id response))success
           failure:(void(^)(AFHTTPRequestOperation *operetion,id response))failure{
    
    if (operation.error) {
        
        if (operation.error.code == 3840) {
            failure(operation,[NSDictionary dictionaryWithObjects:@[@"3804", DNNSLocalizedString(@"Response_FromatError",@"")] forKeys:@[NET_SUCCESS, NET_ERROR_MSG]]);
            return;
        }else if (operation.error.code == -1004)
        {
            failure(operation,[NSDictionary dictionaryWithObjects:@[@"-1004", DNNSLocalizedString(@"Response_ConnectError",@"") ] forKeys:@[NET_SUCCESS, NET_ERROR_MSG]]);
            return;
        }else
        {
            NSString *code = [NSString stringWithFormat:@"%ld",(long)operation.error.code];
            failure(operation,[NSDictionary dictionaryWithObjects:@[code, operation.error.localizedDescription] forKeys:@[NET_SUCCESS, NET_ERROR_MSG]]);
            return;
        }
    }else{
        NSDictionary *responseDic = (NSDictionary *)response;
        
        if (![responseDic isKindOfClass:[NSDictionary class]] || ![responseDic objectForKey:NET_SUCCESS]) {
            failure(operation,[NSDictionary dictionaryWithObjects:@[@"401",  DNNSLocalizedString(@"Response_NetworkError",@"")] forKeys:@[NET_SUCCESS, NET_ERROR_MSG]]);
            return;
        }
        
        if ([[responseDic objectForKey:NET_SUCCESS] integerValue] ==1 )
        {
            if (success)
            {
                success(operation,[responseDic objectForKey:NET_RESULT]);
                return;

            }

        }else{
            if (failure) {
                failure(operation,responseDic);
                return;
            }
        }
    }

}

@end


